import Vue from 'vue'
import http from '@src/util/http'
import TaskEditView from './view/TaskEditView.vue'
import { Loading } from 'element-ui';
import { getAsyncTaskEditAllotInitData } from '@src/api/InitDataApi'
import qs from 'qs';
import platform from '@src/platform';
import { RESOURCE_PREFIX } from '@src/util/linkSwitch';

const componentItem = (initData) => {
  return {
    provide: {
      initData: Object.freeze(initData)
    },
    render(h) {
      return h(TaskEditView);
    }
  }
}

Vue.component('async-component', function(resolve) {
  
  // 需要加loading 打开此注释
  const instance = Loading.service({ fullscreen: true });
  
  let query = qs.parse(window.location.search.substr(1));
  let pathName = window.location.pathname
  if(pathName.indexOf(RESOURCE_PREFIX) > -1) pathName = pathName.replace(RESOURCE_PREFIX, '')
  let params = Object.assign({}, query, {})
  // 是否带id的url
  const isIdUrl = [
    { path:'/task/edit', type:'taskId' },
    { path:'/task/noFilterEdit', type:'taskId' },
    { path:'/task/createFromCustomer', type:'id' },
    { path:'/task/createFromProduct', type:'id' },
  ]
  isIdUrl.forEach(item=>{ 
    if(pathName !== item.path && pathName.includes(item.path) && pathName !== '/task/edit4CallCenter' ){
      const id = window.location.href.substring(window.location.href.lastIndexOf('/') + 1, window.location.href.length).split('?')[0]
      params[item.type] = id
      pathName = pathName.replace(`/${id}`, '')
    }
  })
  const urlList = ['/task/copyTask', '/task/planTask/create', '/task/planTask/edit', '/task/planTask/copy', '/event/convent2Task/jump'] 
  
  let url = ''
  if(urlList.includes(pathName)){
    url = `${pathName}/init` 
  }else if (pathName.indexOf( 'task/noFilterEdit') !== -1){
    url = '/task/editV2/init'
  }else if (pathName.indexOf('task/edit4CallCenter') !== -1){
    url = '/task/edit4CallCenter/init'
  }else{
    url = `${pathName}V2/init` 
  }
  
  getAsyncTaskEditAllotInitData(params, url).then(result => {
    let initData = result?.data?.initJson || {}
    const title = (result && result.data && result.data.title) || ''
    const isSuccess = result.succ || result.success
    
    if (!isSuccess) {
      window.location.href = '/500'
      return 
    }
    
    try {
      window._init = JSON.stringify(initData)
    } catch (error) {
      console.error('initData 赋值失败')
    }
    
    // 需要加loading 打开此注释
    instance.close();
    
    if (window.frameElement) {
      const currentTabId = window.frameElement.dataset.id;
      platform.setTabTitle({
        id: currentTabId,
        title
      })
    }
    resolve(componentItem(initData))
    
  }).catch(error => {
    console.error(error)
    window.location.href = '/500'
  })
  
});

let app = {
  render(h) {
    return <async-component />
  }
}

export default app;
